package com.lzx.shop.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzx.shop.dataobject.UserDO;
import com.lzx.shop.enums.RoleEnum;
import com.lzx.shop.model.Result;
import com.lzx.shop.service.UserService;
import com.lzx.shop.utils.HttpRequest;
import com.lzx.shop.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 刘正星
 * @version 1.0.0
 * @ClassName UserApi.java
 * @Description TODO
 * @createTime 2021年03月20日 23:49:00
 */
@Api(tags = "UserApi", description = "用户信息管理")
@RestController
@RequestMapping("/user")
public class UserApi {

    @Autowired
    private UserService userService;

    @ApiOperation("插入用户")
    @PostMapping("/save")
    public Result saveUser(@RequestBody UserDO userDO) {

        boolean result = userService.save(userDO);

        return ResultUtil.success(result);

    }

    @ApiOperation("查询所有用户")
    @GetMapping("/list")
    public Result userList() {
        List<UserDO> userDOS = userService.findAll();
        return ResultUtil.success(userDOS);
    }

    @ApiOperation("更新")
    @PostMapping("/update")
    public Result update(@RequestBody UserDO userDO) {
        return ResultUtil.success(userService.update(userDO));
    }

    @ApiOperation("根据id删除")
    @DeleteMapping("/del/{id}")
    public Result del(@PathVariable("id") String id) {

        if (StringUtils.isBlank(id)) {
            return ResultUtil.paramError();
        }
        boolean result = userService.DeleteById(id);
        return ResultUtil.success(result);
    }

    @ApiOperation("分页查询")
    @GetMapping("/page")
    public Result selectPage(@RequestParam("pageSize") Integer pageSize, @RequestParam("pageNum") Integer pageNum) {
        Page<UserDO> page = new Page<>(pageNum, pageSize);

        IPage userPage = userService.selectPage(page, null);
        return ResultUtil.success(userPage);
    }

    @GetMapping("/miniapp/login")
    public Result login(@RequestParam("code") String code) {
        if (StringUtils.isBlank(code)) {
            return ResultUtil.paramError();
        }
        String openid = getOpenid(code);


        //openid存在，则查找该user对象进行返回
        UserDO userDO = userService.query(new QueryWrapper<UserDO>().eq("openid", openid));

        return ResultUtil.success(userDO);

    }

    @PostMapping("/miniapp/reg")
    public Result miniAppReg(@RequestParam("code") String code, @RequestBody UserDO userDO) {
        if (StringUtils.isBlank(code)) {
            return ResultUtil.paramError();
        }
        if (userDO == null) {
            return ResultUtil.paramError();
        }
        String openid = getOpenid(code);
        userDO.setOpenid(openid);
        if (userService.exits(openid)) {
            return ResultUtil.customResultParam(true, "0", "用户已经存在", true);
        }
        userDO.setRole(RoleEnum.CUSTOMER.toString());
        boolean result = userService.save(userDO);
        return ResultUtil.success(result);
    }


    /**
     * 根据code获取openid
     *
     * @param code
     * @return
     */

    private String getOpenid(String code) {

        //小程序唯一标识   (在微信小程序管理后台获取)
        String wxspAppid = "wxced7a85f89382cbd";
        //小程序的 app secret (在微信小程序管理后台获取)
        String wxspSecret = "9120c347d1373920cc1c57acaa5bf6c0";
        //授权（必填）
        String grant_type = "authorization_code";

        // 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
        //请求参数
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        //发送请求
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        //解析相应内容（转换成json对象）
        JSONObject json = JSONObject.parseObject(sr);
        //用户的唯一标识（openid）
        String openid = (String) json.get("openid");
        return openid;
    }


}
